import appConf from '../../confs/appConf';
import Dialog from '../ui/Dialog';
import Loading from '../ui/Loading';
import BindPhoneDlg from '../ui/BindPhoneDlg';
import RenZhengDlg from '../ui/RenZhengDlg';
const fs = wx.getFileSystemManager();
let loading = null;
let dlg = null;
let confirm = null;
let bindPhoneDlg = null;
let renZhengDlg = null;

// 用于适配全面屏
const scaleAspect = window.innerHeight / window.innerWidth / (1334 / 750);
const dpr = window.devicePixelRatio || 2;

export function getPaddingTop(isCenter = true) {
  return isCenter ? (1334 * (scaleAspect - 1)) / 2 : 0;
}

export function getAspect() {
  return scaleAspect;
}

/**
 *设计稿横坐标转屏幕坐标
 *
 * @param {number} value
 * @returns 屏幕横坐标
 */
export function getScreenX(value) {
  return (value * window.innerWidth) / 750;
}

/**
 *设计稿纵坐标转屏幕坐标
 *
 * @param {number} value
 * @param {boolean} scaleHeight 是否缩放到高度铺满，大于16:9会被拉伸
 * @returns 屏幕纵坐标
 */
export function getScreenY(value, scaleHeight = false) {
  if (scaleHeight) {
    return (value * window.innerHeight) / 1334;
  }
  return (value * window.innerHeight) / 1334 / scaleAspect;
}

/**
 *屏幕横坐标转设计稿坐标
 *
 * @param {number} value
 * @returns 设计稿横坐标
 */
export function getDesignX(value) {
  return (value / window.innerWidth) * 750;
}

/**
 *屏幕纵坐标转设计稿坐标
 *
 * @param {number} value
 * @param {boolean} scaleHeight 是否缩放到高度铺满，大于16:9会被拉伸
 * @returns 设计稿纵坐标
 */
export function getDesignY(value, scaleHeight = false) {
  if (scaleHeight) {
    return (value / window.innerHeight) * 1334;
  }
  return (value / window.innerHeight) * 1334 * scaleAspect;
}

export function IsLogin() {
  let token = wx.getStorageSync('token');
  if (token) return true;
  return false;
}

export function setToken(token) {
  wx.setStorageSync('token', token);
}

export function getToken() {
  return wx.getStorageSync('token') || '';
}

export function getWxUserInfo() {
  return new Promise((resolve, reject) => {
    wx.getUserInfo({
      success: (res) => {
        resolve(res.userInfo);
      },
      fail: () => {
        resolve();
      },
    });
  });
}

export function setLocUserInfo(userInfo) {
  wx.setStorageSync('user', userInfo);
}

export function getLocUserInfo() {
  return wx.getStorageSync('user') || '';
}

export function setLocUserPhone(phone) {
  let user = wx.getStorageSync('user') || '';
  if (user) {
    user.phone = phone;
    wx.setStorageSync('user', user);
  }
}

export function updateLocSet(set) {
  let user = wx.getStorageSync('user') || '';
  if (user) {
    Object.assign(user, set);
    wx.setStorageSync('user', user);
  }
}

export function updateLocUserPoint(addPoint) {
  let user = wx.getStorageSync('user') || '';
  if (user) {
    user.point += addPoint;
    wx.setStorageSync('user', user);
  }
}

export function clearLocalInfo() {
  wx.removeStorageSync('token');
  wx.removeStorageSync('user');
}

export function showLoading(msg, showBtn = false, callback = () => {}) {
  // wx.showLoading({
  //     title: msg,
  //     mask: true
  // })
  if (!loading) {
    loading = new Loading(msg, showBtn, callback);
  }
  loading.show(msg, showBtn, callback);
}

export function hideLoading() {
  // wx.hideLoading()
  if (loading) loading.hide();
}

export function showAlert(msg, title = '提示', btnTxt = '确定', callback = () => {}) {
  if (!dlg) {
    console.log('new alert dlg');
    dlg = new Dialog(title, msg, false, btnTxt);
    dlg.onOk(callback);
    dlg.show();
  } else {
    console.log('reset alert dlg');
    dlg.resetDlg(title, msg, false, btnTxt);
    dlg.onOk(callback);
    dlg.show();
  }
}

export function showConfirm(msg, title = '提示', callbackOk = () => {}, callbackNo = () => {}) {
  if (!confirm) {
    console.log('new confirm dlg');
    confirm = new Dialog(title, msg, true, '是', '否');
    confirm.onOk(callbackOk);
    confirm.onCancel(callbackNo);
    confirm.show();
  } else {
    console.log('reset confirm dlg');
    confirm.resetDlg(title, msg, true, '是', '否');
    confirm.onOk(callbackOk);
    confirm.onCancel(callbackNo);
    confirm.show();
  }
  return confirm;
}

export function showToast(title = '', duration = 3000) {
  wx.showToast({
    title,
    icon: 'none',
    duration,
  });
}

export function showBindPhoneDlg() {
  if (!bindPhoneDlg) {
    bindPhoneDlg = new BindPhoneDlg();
  }
  bindPhoneDlg.show();
}

export function showRenZhengDlg() {
  if (!renZhengDlg) {
    renZhengDlg = new RenZhengDlg();
  }
  renZhengDlg.show();
}

export function clipTxt(txt, len) {
  return txt && txt.length > len ? txt.substring(0, len) : txt;
}

export function showBoard(txt) {
  wx.showKeyboard({
    defaultValue: txt,
  });
}

export function formatDate(strTime) {
  let date = new Date(strTime);
  return date.getFullYear() + '-' + (date.getMonth() + 1).toString() + '-' + date.getDate();
}

export function formatDate2(strTime) {
  let date = new Date(strTime);
  return date.getFullYear() + '年' + (date.getMonth() + 1).toString() + '月' + date.getDate() + '日';
}

export function formatDate3(strTime) {
  let date = new Date(strTime);
  return (
    date.getFullYear() +
    '.' +
    (date.getMonth() + 1).toString() +
    '.' +
    date.getDate() +
    ' ' +
    date.getHours() +
    ':' +
    date.getMinutes() +
    ':' +
    date.getSeconds()
  );
}

export function isPhoneNum(phone) {
  let regMobile = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
  return regMobile.test(phone);
}

export function isIDS(ids) {
  let IDReg =
    /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/;
  return IDReg.test(ids);
}

export function getFont(size, bold = false) {
  let ahead = bold ? 'bold' : '';
  return `${ahead} ${size}px ${appConf.fontFamily}`;
}

//格式化time
// Common functions
function pad(number, length) {
  let str = '' + number;
  while (str.length < length) {
    str = '0' + str;
  }
  return str;
}
//格式化time(s)
export function formatTime(time) {
  let min = parseInt(time / 60),
    sec = time - min * 60;
  return (min > 0 ? pad(min, 2) : '00') + ':' + pad(sec, 2);
}

export function throttle(method, delay) {
  let timer = null;
  return function () {
    let context = this,
      args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      method.apply(context, args);
    }, delay);
  };
}

export function GetAge(identityCard) {
  var len = (identityCard + '').length;
  if (len == 0) {
    return 0;
  } else {
    if (len != 15 && len != 18) {
      //身份证号码只能为15位或18位其它不合法
      return 0;
    }
  }
  var strBirthday = '';
  if (len == 18) {
    //处理18位的身份证号码从号码中得到生日和性别代码
    strBirthday = identityCard.substr(6, 4) + '/' + identityCard.substr(10, 2) + '/' + identityCard.substr(12, 2);
  }
  if (len == 15) {
    strBirthday = '19' + identityCard.substr(6, 2) + '/' + identityCard.substr(8, 2) + '/' + identityCard.substr(10, 2);
  }
  //时间字符串里，必须是“/”
  var birthDate = new Date(strBirthday);
  var nowDateTime = new Date();
  var age = nowDateTime.getFullYear() - birthDate.getFullYear();
  //再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
  if (
    nowDateTime.getMonth() < birthDate.getMonth() ||
    (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())
  ) {
    age--;
  }
  return age;
}

/**
 * 在球面上随机取一个点
 * 球面从0度到360度每10度做一经线，共0-35，36个经线
 * 纬线：0海拔一条，两边各9条，南北极各成为一个点，共19个纬线
 * 表面上一共614个点
 */
export function getRandomPoint(R) {
  let point = {};
  //取0-35的随机数
  let xjiao = Math.floor(Math.random() * 36);
  //取0-34的随机数
  let yjiao = Math.floor(Math.random() * 10);

  let ta = (xjiao * 10 * Math.PI) / 180;
  let tb = (yjiao * 10 * Math.PI) / 180;
  let tR = R * Math.cos(ta);
  let z = R * Math.sin(ta);
  let x = tR * Math.cos(tb);
  let y = tR * Math.sin(tb);

  if (yjiao == 9) {
    //y在南北两极时，x只能等于0
    x = 0;
  }
  let yzf = [1, 2][Math.round(Math.random())];

  if (yzf == 1) {
    y = -1 * y;
  }

  point.x = x;
  point.y = y;
  point.z = z;

  return point;
}

// 返回一个随机颜色，排除红色
export function getRandomColor() {
  let color = Math.floor(Math.random() * 16777215);
  return color == 0xff0000 ? getRandomColor() : color;
}

